package org.devlabs35.javamail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;

public class ContentFileSaver {
	public static void writeToFile(Part p) throws IOException, MessagingException {
		InputStream inputStream = (InputStream) p.getContent();
		byte[] bArray = new byte[inputStream.available()];
		while (((int) inputStream.available()) > 0) {
			int result = (int) (inputStream.read(bArray));
			if (result == -1)
				break;
		}
		File file = new File("C:\\temp\\" + p.getFileName());
		@SuppressWarnings("resource")
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(bArray);
		System.out.println("Saved at " + file.getAbsolutePath());

	}

	private static void writePlaintextToFile(Message message) throws IOException, MessagingException {
		String content = (String) message.getContent();
		String formattedPlainText = new String(content.getBytes("ISO-8859-1"), "UTF-8");
		File file = new File("C:\\temp\\" + "plaintext.html");

		@SuppressWarnings("resource")
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(formattedPlainText.getBytes());
		System.out.println(file.getAbsolutePath());

	}

}
